<?php
namespace App\Controller;

use Think\Upload;
use App\Logic\AuthLogic;

class BaseController
{
    public function __construct()
    {
		if(ini_get('magic_quotes_gpc')) {
			json(0, 'php请关闭magic_quotes_gpc和magic_quote_runtime');
		}
        if($_SERVER['REQUEST_METHOD'] ==  'OPTIONS') {
            exit('预检请求');
        }

        $params = file_get_contents("php://input"); //兼容非post模式
        if($params && !$_POST) {
            $_POST = json_decode($params, true);//post
            $_REQUEST = array_merge($_POST, $_GET);
        }

        $apiName = '/'.strtolower(CONTROLLER_NAME.'/'.ACTION_NAME);

        //免登录接口
        $allow = array(
			'/index/login',
			'/index/auth',
			'/index/member_sync',
			'/index/department_sync',
			'/index/department_del_sync',
			'/notice/job',
			'/index/download',
			'/ueditor/config',
		);
        if(in_array($apiName, $allow)) {
            return true;
        }

        //验证登录
        $token = $_SERVER['HTTP_ACCESS_TOKEN'];
        if(isset($_GET['token'])) {
            $token = $_GET['token'];
        }
        if(!$token && !$_SERVER['HTTP_ORIGIN'] && PHP_OS == 'WINNT') $token = 'test_token';    //测试token,如果想浏览器直接打开测试接口,可以去掉注释
        if(!$token) {
            json(401, '没有token,请登录');
        }
        $admin_id = $this->checkToken($token);
        define('ADMIN_ID', $admin_id);

        //验证接口权限
        $L = new AuthLogic();
        $rs = $L->checkApi($admin_id, $apiName);
        if(!$rs) {
            json(0, '没有API权限:'.$apiName);
        }
    }

    //验证token
    public function checkToken($token)
    {
        $where = array(
            'token'     =>  $token,
        );
        $rs = M('token')->where($where)->find();
        if(!$rs) {
            json(401, '不存在此token');
        }
        if($rs['exp_ts'] - time() < 0) {
            json(401, 'token已经失效');
        }
        return $rs['admin_id'];
    }

    //文件上传
    public function upload()
    {
        $admin_id = ADMIN_ID;
        if($admin_id < 1){
            json(0, '请登录');
        }
        $config = array(
            'rootPath' => './upload',
            'savePath' => '/files/',
            'saveName' =>  md5_file($_FILES['file']['tmp_name']),
            'exts' => array(),
            'autoSub' => true,
            'subName' => array('date', 'Ymd'),
        );
        $upload = new Upload($config);
        $up_info = $upload->uploadOne($_FILES['file']);
        if($up_info === false){
            json(0, $upload->getError());
        }
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/upload'.$up_info['savepath'].$up_info['savename'];
        json(1, $url);
    }

	//文件下载
	public function download()
	{
		ob_clean();
		$url = I('get.url');
		$path = str_replace('http://' . SITE_DOMAIN . '/', '', $url);
		if(!is_file($path)) exit('文件不存在');
		$content = file_get_contents($path);
		$name = I('get.name');
		header("Content-type:application/octet-stream");
		header("Accept-Ranges:bytes");
		header("Accept-Length:".strlen($content));
		header("Content-Disposition: attachment; filename=".$name);
		echo $content;exit;
	}

    /**
     * 导入excel表格公共部分
     * @param $ths  参考wage/import
     */
    public function import_common($ths)
    {
		$admin_id = ADMIN_ID;
        if($admin_id < 1){
            json(0, '请登录');
        }
        $name = $_FILES['file']['name'];
        $file = $_FILES['file']['tmp_name'];


        if(!$name){
            json(0, '请选择文件');
        }
        if($_FILES['file']['error'] !== 0 && !$_GET['debug']){
            json(0, '文件上传错误码'.$_FILES['file']['error']);
        }

        //数据
        $ext = fileExt($name);
        if(!in_array($ext, array('xls', 'xlsx'))){
            json(0, '文件格式错误');
        }

        $tp = ($ext == 'xls') ? 'Excel5' : 'Excel2007';
        $sheets = readExcelToArray($file, array(0), $tp);
        $sheets = $sheets['sheet_0'];
        if(empty($sheets)){
            json(0, '没有数据');
        }

        //去除空字段
        foreach($sheets[0] as $k => $v) {
            $v = trim($v);
            if($v == '') {
                unset($sheets[0][$k]);
            }
        }

        //表头验证
        $rs = diff_array(array_keys($ths), $sheets[0]);
        if($rs !== true) {
            json(0, $rs);
        }

        //拼接数组
        $data = array();
        foreach($sheets as $k => $v) {
            if($k == 0) continue;
            if(!$v[0] && !$v[1] && !$v[2]) continue;
            foreach($v as $k => &$c) {
                if($k >= count($sheets[0])) unset($v[$k]);
                $c = trim($c);
            }
            $data[] = array_combine(array_values($ths), $v);
        }
        return $data;
    }

    /**
     * 导入错误信息
     * @param $err  错误数组
     */
    public function import_error($err)
    {
        $str = '';
        foreach($err as $type => $rows)
        {
            $str .= '<h3 style="color:#00d;margin-top:12px; font-size:16px;">'.$type.'</h3><br/>';
            foreach($rows as $row) {
                $str .= $row.'<br/>';
            }
        }
        json(0, $str);
    }

	/**
	 * 简易模板
	 *
	 * @param string $_tpl	模板文件名，不包含扩展名
	 * @param array $data	赋值给模板的数组，例如array('title'=>'标题')
	 * @param string $dir	模板目录
	 */
	function display($_tpl, $data = array())
	{
		extract($data);
		$_title = "网站标题";
		include(APP_PATH.'App/View/'.$_tpl.'.html');
	}
}